#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

int main(int argc,char *argv[]){
  int serversock,clientsock;
  struct sockaddr_in mesgserver,mesgclient;
  struct sockaddr_in *addr;
  socklen_t length_ptr;

  length_ptr=sizeof(struct sockaddr_in);
  addr=malloc(length_ptr);

  if ((serversock=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
    printf("couldn't create socket\n");
    exit(-1);
  }

  /* Construct the server sockaddr_in structure */
  memset(&mesgserver, 0, sizeof(mesgserver));       /* Clear struct */
  mesgserver.sin_family = AF_INET;                  /* Internet/IP */
  mesgserver.sin_addr.s_addr = htonl(INADDR_ANY);   /* Incoming addr */
  mesgserver.sin_port = htons(50090);          /* server port */
  
  /* Bind the server socket */
  if (bind(serversock, (struct sockaddr *) &mesgserver,
	   sizeof(mesgserver)) < 0){
    printf("failed to bind on socket\n");
    exit(-1);
  }

  /* Listen on the server socket */
  if (listen(serversock, 5) < 0){
    printf("failed to listen\n");
    exit(-1);
  }

  while(1){
    unsigned int clientlen = sizeof(mesgclient);    
    if ((clientsock=accept(serversock,
			   (struct sockaddr *)&mesgclient,
			   &clientlen))<0){
      printf("failed to accept client connection\n");
      exit(-1);
    } else {
      getsockname(clientsock,(struct sockaddr *)addr,&length_ptr);
      
      printf("connected on IP %s\n",
	     inet_ntoa(addr->sin_addr));
      close(clientsock);
    }
  }
  close(serversock);
  
  exit(0);
}
